import { getRepository } from 'typeorm';
import { UserEntity } from '../entity/user.entity';
import { encrypt, Bcrypt } from '../utils/crypto';
import { simpleUUID } from '../utils/uuid';

const userRepository = getRepository(UserEntity);
const bcrypt = new Bcrypt();

export async function login(entity: UserEntity) {
  // return await userRepository.findOne({
  //   username: entity.username,
  //   password: encrypt(entity.password)
  // });
  const user = await userRepository.findOne({
    username: entity.username
  });
  let result: UserEntity;
  if (user && bcrypt.compare(entity.password, user.password)) {
    result = user;
  }
  return result;
}

export async function register(entity: UserEntity) {
  const result = await userRepository.findOne({
    username: entity.username
  });
  if (result) return -1;
  entity.id = simpleUUID();
  // entity.password = encrypt(entity.password);
  entity.password = bcrypt.hash(entity.password);
  const { raw } = await userRepository.insert(entity);
  return raw.affectedRows;
}

export async function update(id: string, entity: UserEntity) {
  // entity.password = encrypt(entity.password);
  entity.password = bcrypt.hash(entity.password);
  const { affected } = await userRepository.update(id, entity);
  return affected;
}

export async function select(id?: string) {
  if (id) {
    return await userRepository.findOne(id);
  }
  return await userRepository.find();
}
